package com.ls.lserp.modules.purchase.service;




import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.inventoryControl.dao.InventoryDao;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.purchase.dao.PurchaseContractDao;
import com.ls.lserp.modules.purchase.entity.PurchaseAdvance;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.setting.dao.InventoryWarningDao;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.sys.entity.Brand;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;
@Service
@Transactional(readOnly = false)
public class PurchaseContractService extends CrudService<PurchaseContractDao,PurchaseContract>{

	//合同
	 @Autowired
		private PurchaseContractDao purchaseContractDao ;
	 @Autowired
	 private InventoryWarningDao inventoryWarningDao;
	// 审核表
			@Autowired
				private AuditInfoDao  auditInfoDao;

		/**
		 * 查询父项
		 * @param page
		 * @param user
		 * @return
		 */
		public Page<PurchaseContract> findPurchaseContractList(Page<PurchaseContract> page, PurchaseContract purchaseContract) {
			// 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
			//designOption.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
			// 设置分页参数
			purchaseContract.setPage(page);
			// 执行分页查询
			page.setList(purchaseContractDao.findList(purchaseContract));
			return page;
		}
		/**
		 * 查询原辅料信息
		 * 
		 * @param user
		 * @return
		 */
		public List<PurchaseContract> searchMaterialList(PurchaseContract purchaseContract) {
			
			return purchaseContractDao.searchMaterialList(purchaseContract);
			
		}
		
		/**
		 * 查询原辅料信息
		 * 
		 * @param user
		 * @return
		 */
		public List<PurchaseContract> findMaterialList(PurchaseContract purchaseContract) {
			
			return purchaseContractDao.findMaterialList(purchaseContract);
			
		}
	/**
	 * 查询库存预警信息
	 *
	 * @param purchaseContract
	 * @return
	 */
	public List<PurchaseContract> findMaterialAlertList(PurchaseContract purchaseContract) {

		return purchaseContractDao.findMaterialAlertList(purchaseContract);

	}
		/**
		 * ID查询原辅料信息
		 * 
		 * @param user
		 * @return
		 */
		public List<PurchaseContract> findMaterialByIdMTM(PurchaseContract purchaseContract) {
			
			return purchaseContractDao.findMaterialByIdMTM(purchaseContract);
			
		}
		
		/**
		 * ID查询原辅料信息
		 * 
		 * @param user
		 * @return
		 */
		public List<PurchaseContract> findMaterialByIdOrder(PurchaseContract purchaseContract) {
			
			return purchaseContractDao.findMaterialByIdOrder(purchaseContract);
			
		}
		
		/**
		 * ID查询原辅料信息(库存预警)
		 * 
		 * @param user
		 * @return
		 */
		public List<PurchaseContract> findMaterialByIdAlert(PurchaseContract purchaseContract) {
			
			return purchaseContractDao.findMaterialByIdAlert(purchaseContract);
			
		}
		
		/**
		 * 获取甲方信息	 
		 * @param ognization
		 * @return
		 */
		public Ognization getPartyA(Ognization ognization) {
			
			return purchaseContractDao.getPartyA(ognization);
		}
		/**
		 * 查询一条采购合同信息
		 * 
		 * @param user
		 * @return
		 */
		public PurchaseContract getContract(PurchaseContract purchaseContract) {
			
			return purchaseContractDao.get(purchaseContract);
			
		}
		/**
		 * 获取客户供货商
		 * @return
		 */
		public List<Ognization> findOgnizationList(){
			return purchaseContractDao.findOgnizationList();
		}
		
		/**
		 * 获取品牌
		 * @return
		 */
		public List<Brand> findBrandList(Long ognizationId){
			List<Brand> brandIDList = new ArrayList<>();
			Material material = new Material();
			// 查询供应厂对应的品牌个数
			String brandVar = purchaseContractDao.selectBrankId(ognizationId);
				ArrayList alBrandTemp = new ArrayList();
				if (brandVar != null && brandVar != "") {
					String [] barndTemp = brandVar.split(",");
					for (int i = 0; i < barndTemp.length; i++){
						alBrandTemp.add(barndTemp[i]);
					}
				}
				material.setBrandIDList(alBrandTemp);
				// 查询对应的品牌中文
				brandIDList = purchaseContractDao.selectBrankNameCn(material);
				return brandIDList;
		}
		
		/**
		 * 获取合同条款
		 * 
		 * @param user
		 * @return
		 */
		public PurchaseContract getClause(PurchaseContract purchaseContract) {
			
			return purchaseContractDao.getClause(purchaseContract);
			
		}
		
		/**
		 * ID查询一条数据
		 * 
		 * @param user
		 * @return
		 */
		public PurchaseContract findByID(Long id){
			
			return purchaseContractDao.get(id);
		}
		
		/**
		 * 查询面料是否已创建采购
		 * 
		 * @param user
		 * @return
		 */
		public String checkMaterial(String materialIDStr,String purchaseType,String ognizationIDB){
			if(materialIDStr != null){
				String[] materialIDList = materialIDStr.split(",");
				List<PurchaseContract> mList = new ArrayList<>();
				for (int i = 0; i < materialIDList.length; i++) {
					//定制采购
					if (ResourcesUtil.getConfig("purchaseType_10").equals(purchaseType)) {
						mList = purchaseContractDao.findPurchaseMaterialMtm(materialIDList[i],ResourcesUtil.getConfig("purchase_status_20"));
					//大货、预警
					}else {
						mList = purchaseContractDao.findPurchaseMaterial(materialIDList[i],ResourcesUtil.getConfig("purchase_status_20"),ognizationIDB);
					}
					if (mList != null && mList.size() > 0) {
						return mList.get(0).getMaterialCode();
					}
				}
	    	}	
			return "true";
		}
		
		/**
		 * 更新库存预警状态
		 * 
		 * @param user
		 * @return
		 */
		public void updateAlertStatus(String[] materialIDStr,String ognizationIDB){
			if (materialIDStr != null) {
				if (materialIDStr.length > 0) {
					for (int i = 0; i < materialIDStr.length; i++) {
						purchaseContractDao.updateReserverPurchaseStatus(materialIDStr[i], ognizationIDB, "1",ResourcesUtil.getConfig("inventoryAlert_00"));
						inventoryWarningDao.updateAlertStatus(materialIDStr[i],ResourcesUtil.getConfig("inventoryAlert_10"),ResourcesUtil.getConfig("inventoryAlert_00"));
					}
				}
			}
			
		}
		
		/**
		 * 新增/修改一条数据
		 * @param user
		 */
		@Transactional(readOnly = false)
		public void savePurchaseContract(PurchaseContract purchaseContract) {
			// 判断新建编辑
				//若为null 执行插入语句（新建）
				if (purchaseContract.getId()==null){
					// 编辑
					String shortName = purchaseContract.getOgnizationShortNameB();
					StringBuilder conCode = new StringBuilder();
					conCode.append("130");
					conCode.append(shortName);
					conCode.append(DateUtils.formatDate(new Date(), "yyyy"));
					conCode.append("20");
					Sequence sequence=SequenceUtil.ognizationCode(conCode.toString(), "sequence_purchaseContact", 4);
					purchaseContract.setContractMaterialNO(sequence.getReturnCode());
					purchaseContract.preInsert();
					purchaseContract.setContractAuditStatus(ResourcesUtil.getConfig("audit_uncommit"));
					purchaseContractDao.insert(purchaseContract);
					if (purchaseContract.getMaterialList()!=null) {
						for (int i = 0; i < purchaseContract.getMaterialList().size(); i++) {
							PurchaseContract purchaseContract_T =  purchaseContract.getMaterialList().get(i);
							if (purchaseContract_T.getMaterialID()==null) {
								continue;
							}
							purchaseContract_T.setId(purchaseContract.getId());
							purchaseContract_T.preInsert();
							purchaseContractDao.insertDetail(purchaseContract_T);
							purchaseContractDao.insertmaterialCost(purchaseContract_T);
						}
					}
						
				}else{
					// 更新数据
					purchaseContract.preInsert();
					purchaseContractDao.update(purchaseContract);
					purchaseContractDao.deleteDetail(purchaseContract);
					purchaseContractDao.deletematerialCost(purchaseContract);
					if (purchaseContract.getMaterialList()!=null) {
						for (int i = 0; i < purchaseContract.getMaterialList().size(); i++) {
							PurchaseContract purchaseContract_T =  purchaseContract.getMaterialList().get(i);
							if (purchaseContract_T.getMaterialID()==null) {
								continue;
							}
							purchaseContract_T.setId(purchaseContract.getId());
							purchaseContract_T.setVersion(purchaseContract.getVersion());
							purchaseContract_T.preInsert();
							purchaseContractDao.insertDetail(purchaseContract_T);
							purchaseContractDao.insertmaterialCost(purchaseContract_T);
						}
					}
				}			
		}
		/**
		 * 提交一条数据
		 * @param user
		 */
		@Transactional(readOnly = false)
		public void commitPurchaseContract(PurchaseContract purchaseContract) {
			// 判断新建编辑
					// 更新数据
					purchaseContract.preInsert();
					purchaseContract.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_wait_accept"));
					purchaseContractDao.commitUpdate(purchaseContract);
		}
		/**
		 * 删除一条数据
		 * @param user
		 */
		@Transactional(readOnly = false)
		public void deletePurchaseContract(PurchaseContract purchaseContract) {
			// 判断新建编辑
					// 更新数据
					purchaseContract.preInsert();
					purchaseContractDao.delete(purchaseContract);
		}
		
		/**
		 * @Title: findAuditList
		 * @Description: 查询所有履历
		 * @param @param auditInfo
		 * @param @return
		 * @return List<AuditInfo> 
		 * @throws
		 */
	   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
		   AuditInfo audit = new AuditInfo();
		   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
		   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
		   // 执行查询
		   return audit;
	   }
	   /**
		* @Title: getAuditResult
		* @Description: 审核结果
		* @param @param auditInfo
		* @param @return
		* @return 审核结果通过数
		* @throws
		*/
	  
	  public long getAuditResult(AuditInfo auditInfo) {
		   
		  return auditInfoDao.findAuditAcceptCount(auditInfo);
	  }
	  
	  /**
		  * @Title: saveAudit
		  * @Description: 保存履历信息
		  * @param @param auditInfo
		  * @return void 
		  * @throws
		  */
		@Transactional(readOnly = false)
		public void saveAuditInfo(AuditInfo auditInfo,boolean isUpdateStatus) {
			
			 // 插入履历表
			 auditInfo.preInsert();
			 auditInfo.setAuditDate(new Date());
			 auditInfo.setAuditUserId(UserUtils.getUser().getId());
			 // 新建版本号赋值1
			 auditInfo.setVersion(1L);
			 auditInfoDao.insert(auditInfo);
			 
			 auditInfo.preUpdate();
			 if (auditInfo.getAuditResult()==0) {
				 auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
			}else if (auditInfo.getAuditResult()==1) {
				auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
				 purchaseContractDao.updateContractStatus(auditInfo);
				 purchaseContractDao.updateContractDetailStatus(auditInfo);
			}
			 
			 purchaseContractDao.updateStatus(auditInfo);
			 
		}
		/**
		 * 导出采购合同
		 *
		 * @throws IOException
		 */
		public ExcelTemplate export(PurchaseContract purchaseContract, String tempFilePath) throws IOException {
			// 返回值
			ExcelTemplate handle = new ExcelTemplate();
			// 输出采购合同信息
			printPurchaseContractInfoTemp(tempFilePath, purchaseContract, handle);
			if (purchaseContract.getMaterialList() != null && purchaseContract.getMaterialList().size() > 0 ) {
				// 输出采购原辅料信息
				printMaterialListInfoTemp(tempFilePath,purchaseContract.getPurchaseType(), purchaseContract.getMaterialList(), handle);
			}
			return handle;

		}
		private void printPurchaseContractInfoTemp(String tempFilePath, PurchaseContract purchaseContract, ExcelTemplate handle) throws IOException {
			List<String> dataCellDeclare = new ArrayList<String>();
			// 变量值
			Map<String, Object> dataMapResult = new HashMap<String, Object>();
			// 格式化数字
			NumberFormat num = NumberFormat.getInstance();
			
			// 甲方公司
			dataCellDeclare.add("ognizationNameA");
			dataMapResult.put("ognizationNameA", purchaseContract.getOgnizationNameA());
			
			// 乙方公司
			dataCellDeclare.add("ognizationNameTempB");
			dataMapResult.put("ognizationNameTempB", purchaseContract.getOgnizationNameB());
			
			// 甲方住所地
			dataCellDeclare.add("ognizationAddressA");
			dataMapResult.put("ognizationAddressA", purchaseContract.getOgnizationAddressA());
			// 乙方住所地
			dataCellDeclare.add("ognizationAddressB");
			dataMapResult.put("ognizationAddressB", purchaseContract.getOgnizationAddressB());
			// 甲方法人代表
			dataCellDeclare.add("legalPersonA");
			dataMapResult.put("legalPersonA", purchaseContract.getLegalPersonA());
			// 甲方主联系人
			dataCellDeclare.add("contactPersonA");
			dataMapResult.put("contactPersonA", purchaseContract.getContactPersonA());
			// 乙方法人代表
			dataCellDeclare.add("legalPersonB");
			dataMapResult.put("legalPersonB", purchaseContract.getLegalPersonB());
			// 乙方主联系人
			dataCellDeclare.add("contactPersonB");
			dataMapResult.put("contactPersonB", purchaseContract.getContactPersonB());
			// 甲方联系电话
			dataCellDeclare.add("contactPhoneA");
			dataMapResult.put("contactPhoneA", purchaseContract.getContactPhoneA());
			// 甲方传真号码
			dataCellDeclare.add("contactFaxA");
			dataMapResult.put("contactFaxA", purchaseContract.getContactFaxA());
			// 乙方联系电话
			dataCellDeclare.add("contactPhoneB");
			dataMapResult.put("contactPhoneB", purchaseContract.getContactPhoneB());
			// 乙方传真号码
			dataCellDeclare.add("contactFaxB");
			dataMapResult.put("contactFaxB", purchaseContract.getContactFaxB());
			// 甲方电子邮箱
			dataCellDeclare.add("contactEmailA");
			dataMapResult.put("contactEmailA", purchaseContract.getContactEmailA());
			// 乙方电子邮箱
			dataCellDeclare.add("contactEmailB");
			dataMapResult.put("contactEmailB", purchaseContract.getContactEmailB());
			// 付款方式
			dataCellDeclare.add("paymentWay");
			dataMapResult.put("paymentWay", purchaseContract.getPaymentWay());
			// 合同状态
			dataCellDeclare.add("contractStatus");
			dataMapResult.put("contractStatus", purchaseContract.getContractStatus());
			// 采购类别
			dataCellDeclare.add("purchaseType");
			dataMapResult.put("purchaseType", purchaseContract.getPurchaseType());
			// 订料总数
			dataCellDeclare.add("contractMaterialQuantity");
			if (purchaseContract.getContractMaterialQuantity() == null || "".equals(purchaseContract.getContractMaterialQuantity())) {
				dataMapResult.put("contractMaterialQuantity", purchaseContract.getContractMaterialQuantity());
			} else {
				dataMapResult.put("contractMaterialQuantity", num.format(purchaseContract.getContractMaterialQuantity()));
			}
			// 订单金额
			dataCellDeclare.add("contractAmount");
			if (purchaseContract.getContractAmount() == null || "".equals(purchaseContract.getContractAmount())) {
				dataMapResult.put("contractAmount", purchaseContract.getContractAmount());
			} else {
				dataMapResult.put("contractAmount", num.format(purchaseContract.getContractAmount()));
			}
			// 特殊说明
			dataCellDeclare.add("specialExplain");
			dataMapResult.put("specialExplain", purchaseContract.getSpecialExplain());
			// 签订日期
			dataCellDeclare.add("contractDateTime");
			if ("".equals(purchaseContract.getContractDateTime()) || purchaseContract.getContractDateTime() == null) {
				dataMapResult.put("contractDateTime", "");
			} else {
				dataMapResult.put("contractDateTime", DateUtils.formatDate(purchaseContract.getContractDateTime(), "yyyy-MM-dd"));
			}
			// 结算日期
			dataCellDeclare.add("contractEndDate");
			dataMapResult.put("contractEndDate", "");
			if ("1".equals(purchaseContract.getClauseType())) {
				// 合同条款
				dataCellDeclare.add("contractClause");
				dataMapResult.put("contractClause", " (3) 结算方式及期限："+purchaseContract.getPaymentWay());
			}
			// 创建人员
			dataCellDeclare.add("firstName");
			dataMapResult.put("firstName", purchaseContract.getCreateBy().getFirstName());
			// 创建时间
			dataCellDeclare.add("createDate");
			if ("".equals(purchaseContract.getCreateDate()) || purchaseContract.getCreateDate() == null) {
				dataMapResult.put("createDate", "");
			} else {
				dataMapResult.put("createDate", DateUtils.formatDate(purchaseContract.getCreateDate(), "yyyy-MM-dd"));
			}
			
			// 开户银行
			dataCellDeclare.add("bankName");
			dataMapResult.put("bankName", purchaseContract.getBankName());
			// 银行账户
			dataCellDeclare.add("bankAccountNo");
			dataMapResult.put("bankAccountNo", purchaseContract.getBankAccountNo());
			
			// 向excel表输出
			handle.writeData(tempFilePath, dataCellDeclare, dataMapResult, 0);
		}
		
		private void printMaterialListInfoTemp(String tempFilePath, String purchaseType, List<PurchaseContract> materialList, ExcelTemplate handle) throws IOException {
			// 变量声明
			List<String> dataCellDeclare = new ArrayList<String>();
			// 变量值集合
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			dataCellDeclare.add("materialCode");
			dataCellDeclare.add("materialSpec");
			dataCellDeclare.add("materialSpecUnitCD");
			if ("定制采购".equals(purchaseType)) {
				dataCellDeclare.add("ognizationNameB");
				dataCellDeclare.add("brandName");
			} else {
				dataCellDeclare.add("ognizationNameB");
				dataCellDeclare.add("contractNO");
				dataCellDeclare.add("reserveQuantity");
				dataCellDeclare.add("realityQuantity");
			}
			dataCellDeclare.add("purchaseUnitPrice");
			dataCellDeclare.add("purchaseReserveQuantity");
			dataCellDeclare.add("purchaseOtherCost");
			dataCellDeclare.add("purchaseAllCost");
			
			// 结果
			Map<String, Object> map;
			// 临时接收变量
			PurchaseContract tempBean;
			// 格式化数字
			NumberFormat num = NumberFormat.getInstance();
			for (int i = 0; i < materialList.size(); i++) {
				map = new HashMap<String, Object>();
				tempBean = materialList.get(i);
				
				// 物料编码
				if ("".equals(tempBean.getMaterialNameCN()) || tempBean.getMaterialNameCN() == null) {
					map.put("materialCode", tempBean.getMaterialCode());
				} else {
					map.put("materialCode", tempBean.getMaterialCode()+"/"+tempBean.getMaterialNameCN());
				}
				// 幅宽
				map.put("materialSpec", tempBean.getMaterialSpec());
				// 单位
				map.put("materialSpecUnitCD", tempBean.getMaterialSpecUnitCD());
				if ("定制采购".equals(purchaseType)) {
					// 客户
					map.put("ognizationNameB", tempBean.getOgnizationNameB());
					// 品牌
					map.put("brandName", tempBean.getBrandName());
				} else {
					// 供货商名称
					map.put("ognizationNameB", tempBean.getOgnizationNameB());
					// 合同订单号
					map.put("contractNO", tempBean.getContractNO());
					// 预订耗料
					map.put("reserveQuantity", tempBean.getReserveQuantity());
					// 已采购数量
					map.put("realityQuantity", tempBean.getRealityQuantity());
				}
				// 采购单价
				if (tempBean.getPurchaseUnitPrice() == null || "".equals(tempBean.getPurchaseUnitPrice())) {
					map.put("purchaseUnitPrice", tempBean.getPurchaseUnitPrice());
				} else {
					map.put("purchaseUnitPrice", num.format(tempBean.getPurchaseUnitPrice()));
				}
				// 采购数量
				if (tempBean.getPurchaseReserveQuantity() == null || "".equals(tempBean.getPurchaseReserveQuantity())) {
					map.put("purchaseReserveQuantity", tempBean.getPurchaseReserveQuantity());
				} else {
					map.put("purchaseReserveQuantity", num.format(tempBean.getPurchaseReserveQuantity()));
				}
				// 其他费用
				if (tempBean.getPurchaseOtherCost() == null || "".equals(tempBean.getPurchaseOtherCost())) {
					map.put("purchaseOtherCost", tempBean.getPurchaseOtherCost());
				} else {
					map.put("purchaseOtherCost", num.format(tempBean.getPurchaseOtherCost()));
				}
				// 采购金额
				if (tempBean.getPurchaseAllCost() == null || "".equals(tempBean.getPurchaseAllCost())) {
					map.put("purchaseAllCost", tempBean.getPurchaseAllCost());
				} else {
					map.put("purchaseAllCost", num.format(tempBean.getPurchaseAllCost()));
				}
				
				dataList.add(map);
			}
			
		 // 向excel表输出
			handle.writeListData(tempFilePath, dataCellDeclare, dataList, 0);
		}
}
